package com.yzg.simple.bio;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author misterWei
 * @create 2019年12月17号:21点16分
 * @mailbox mynameisweiyan@gmail.com
 * <p>
 * <p>
 * 针对BIO 模型 原生开发实现
 * 同步但是阻塞    阻塞点会被阐述
 */
public class BIOServer {

    public static void main(String[] args) throws Exception {
        //线程池对象
        ExecutorService executorService = Executors.newCachedThreadPool();
        //创建服务器对象
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            //1阻塞,用来监听到客户端的链接
            final Socket accept = serverSocket.accept();
            executorService.execute(() -> {
                //单独定义一个方法去处理客户端请求
                System.out.println(Thread.currentThread().getName() + " 客户端链接了");
                hander(accept);
            });
        }
    }

    private static void hander(Socket accept) {
        try {
            byte[] bytes = new byte[1024];
            // 得到客户端的信息
            InputStream inputStream = accept.getInputStream();
            while (true) {
                //2 阻塞,客户端链接之后 阻塞获取客户端的消息
                int read = inputStream.read(bytes);
                if (read != -1) {
                    //得到消息
                    System.out.println(new String(bytes, 0, read));
                    OutputStream outputStream = accept.getOutputStream();
                    outputStream.write(("hello client" + Thread.currentThread().getName()).getBytes());
                    outputStream.flush();
                } else {
                    break;
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                accept.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}
